var refreshIntervalId =0;
var deployQueue=[];
var notificationQueue=[];
var uftDeploy ={
		
		init: function(id){
			$("#deployOptions_"+id).accordion({heightStyle: "fill"});
			$("#deployOutputTab_"+id ).tabs({ heightStyle: "fill" });
			$("#deployloadingImg_"+id ).hide();
			$( "#submit_"+id).button({
                icons: {
                       primary: "ui-icon-pencil"
                     }
            });
            $( "#sendEmail_"+id).button({
                icons: {
                       primary: "ui-icon-mail-closed"
                     },
                     disabled: true
            });
            uftDeploy.submitDeploymentTask(id);
           // uftDeploy.getDeploymentData(id,uftDeploy.updatDeploymentStatus);
		},
	submitNotificationTask: function(uniqueId){
		notificationQueue.push(uniqueId);
	},
	
	submitDeploymentTask: function(id){
		//console.log("adding tasking: "+id);
		deployQueue.push(id);
		//console.log( deployQueue.join());   
	},
	removeDeploymentTask: function(id){
		//deployQueue.push(id);
		//console.log("remove tasking: "+id);
		var i = $.inArray(id,deployQueue);
		//console.log("remove tasking:  index ="+i);
		if (i != -1){
			deployQueue.splice(i, 1);
		}
		//console.log( deployQueue.join() );
	},
	removeNotificationTask: function(uniqueId){
		var i = $.inArray(uniqueId,notificationQueue);
		//console.log("remove tasking:  index ="+i);
		if (i != -1){
			notificationQueue.splice(i, 1);
		}
	},
	updateNotificationButton: function(uniqueId, data){
		
		if (data.Result == "EXISTS") {
			if(data.Status == "COMPLETE"){
				uftDeploy.removeNotificationTask(uniqueId);
				var output=data.Output;
				//var button=$("#taskNotificationBtn").button();
				var btnValue=$("#taskNotificationBtn").text();
				//console.log("bbtnValue: "+btnValue);
				var newValue= parseInt(btnValue)+1;
				//console.log("button value: "+newValue);
				$("#taskNotificationBtn").button('option','label',newValue);
				var array=uniqueId.split("|");
				var serverId=array[2];	
				var now = new Date();
				if(array[0] == "START" || array[0] == "STOP" ){
					var $row = $('#serverListContainer').jtable("getRowByKey",serverId);
					var record = $row.data('record');
					//console.log(record);
					$('#notificationDialog').append("<div><p>"+now.toLocaleString()+"</p><p>" +
							"Server <strong> "+record.serverName+" </strong>on Host:  <strong> "+record.serverHostname+" </strong> Status: "+output+"</p><hr></div>");
					$.pnotify({
					    title: array[0],
					    text: "Server <strong> "+record.serverName+" </strong> &nbsp; on Host:  <strong> "+record.serverHostname+" </strong> &nbsp; Status: "+output,
					    styling: 'jqueryui',
					    animation: 'fade'
					});
				}else if(array[0] == "UPDATE"){
					$('#notificationDialog').append("<div><p>"+now.toLocaleString()+"</p><p><strong>"+array[0]+": </strong>" +
							""+output+"</p><hr></div>");
					$.pnotify({
					    title: array[0],
					    text: "<strong>&nbsp;"+array[0]+": </strong>" +output,
					    styling: 'jqueryui',
					    animation: 'fade'
					});
				}
				
				
				
			}
		}else{
			uftDeploy.removeNotificationTask(uniqueId);
		}
	},
	updatDeploymentStatus: function(id, data){
		if (data.Result == "RUNNING") {
			$("#submit_"+id).attr("disabled", "disabled");
			$("#deployloadingImg_"+id ).show();
		}else{
			$("#submit_"+id).removeAttr("disabled");
			$("#deployloadingImg_"+id ).hide();
			uftDeploy.removeDeploymentTask(id);
			
		}
		$("#status_"+id).val( data.Result );
		if(typeof data.Output != 'undefined'){
			if( data.Output.length > 0 ){
				$( "#output_"+id ).html(data.Output.replace(/\r\n|\r|\n/g,"<br />"));
			}
		}
		if(typeof data.Error != 'undefined'){
			if(data.Error.length > 0 ){
				$('#deployOutputTab_'+id+' ul li a ').each(function(i) {
					if ($(this).text() == "Error") {
						$(this).css("background-color","red");
					}
				});
				$( "#error_"+id ).html(data.Error.replace(/\r\n|\r|\n/g,"<br />"));
				$("#sendEmail_"+id).button( "enable" );
			}
		}
		
		if(typeof data.StartTime != 'undefined'){
			if(data.StartTime.length > 0 ){
	            $("#startTime_"+id).val( data.StartTime );
	        }
		}
		if(typeof data.EndTime != 'undefined'){
			if(data.EndTime.length > 0 ){
		           $("#endTime_"+id).val( data.EndTime );
		     }
		}
	 	
	},
	getDeploymentData: function(server_id,callback){
		$.ajaxq("deploy",{
			type: "POST",
			url: "getDeployStatus.htm",
		    dataType: 'json',
		    global: false,
		    data: {
		    	serverId: server_id
		    },
		    success: function( json ) {
		   // 	console.log("GetDeploymentData "+json);
		    	callback(server_id,json);
		    },
		    error: function( xhr, status ) {
		    	generateDiag("center","error", status);
		    },
		  });  	
	},
	getNotificationData: function(unique_id, callback){
		$.ajaxq("notification",{
			type: "POST",
			url: "getTaskDetails.htm",
		    dataType: 'json',
		    global: false,
		    data: {
		    	uniqueID: unique_id
		    },
		    success: function( json ) {
		   // 	console.log("GetDeploymentData "+json);
		    	callback(unique_id,json);
		    },
		    error: function( xhr, status ) {
		    	generateDiag("center","error", status);
		    },
		  });  
	}
	
		
};
refreshIntervalId = setInterval(function(){
//console.log("monitoring Deploy Queue");````1		```											`						`										
//	for ( var i in deployQueue ) {
	//	console.log("id: "+i);
//		uftDeploy.getDeploymentData(deployQueue[ i ], uftDeploy.updatDeploymentStatus);
//	}
//	for ( var j in notificationQueue ) {
//		uftDeploy.getNotificationData(notificationQueue[ j ], uftDeploy.updateNotificationButton);
//	}
	 for(var i=0, len=deployQueue.length; i < len; i++){
         uftDeploy.getDeploymentData(deployQueue[i], uftDeploy.updatDeploymentStatus);
	 }
	 for(var j=0, len=notificationQueue.length; j < len; j++){
	         uftDeploy.getNotificationData(notificationQueue[j], uftDeploy.updateNotificationButton);
	 }

}, 5000);

function getServerObject(id){
	var data;
	$.ajaxq("deploy",{
		type: "POST",
		url: "getServer.htm",
	    dataType: 'json',
	    data: {
	    	serverId: id
	    },
	    success: function( json ) {
	   // 	console.log("GetDeploymentData "+json);
	    	data= json
	    }
	   
	  }); 
	return data;
}

